﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Unit : MonoBehaviour
{
    [SerializeField]
    [Range(1, 7)]
    private int moveRange = 3;

    [SerializeField] private float moveSpeed;
    private void OnMouseDown()
    {
        GameManager.instance.selectedUnit = this;
        ShowWalkableTiles();
    }

    private void ShowWalkableTiles()
    {
        for (int i = 0; i < GameManager.instance.tiles.Length; i++)
        {
            GameManager.instance.tiles[i].canMove = false;
            float distX = Mathf.Abs(transform.position.x - GameManager.instance.tiles[i].transform.position.x);
            float distY = Mathf.Abs(transform.position.y - GameManager.instance.tiles[i].transform.position.y);

            if (distX + distY <= moveRange)
            {
                //Tile is Walkable or not (without obstacle)
                if (GameManager.instance.tiles[i].canWalk)
                    GameManager.instance.tiles[i].HighlightTile();

            }
        }
    }

    //MARKER 这个方法会在【Tile脚本】中OnMouseDown函数中被【调用】
    public void Move(Transform _trans)
    {
        StartCoroutine(MoveCo(_trans));
    }

    IEnumerator MoveCo(Transform _trans)
    {
        //角色先水平方向移动
        while (transform.position.x != _trans.position.x)
        {
            transform.position = Vector3.MoveTowards(transform.position, new Vector3(_trans.position.x, transform.position.y, transform.position.z), moveSpeed * Time.deltaTime);
            yield return new WaitForSeconds(0);
        }

        //水平方向到达目的地X后，再垂直方向移动
        while (transform.position.y != _trans.position.y)
        {
            transform.position = Vector3.MoveTowards(transform.position, new Vector3(transform.position.x, _trans.position.y, transform.position.y), moveSpeed * Time.deltaTime);
            yield return null;
        }
        ResetTiles();
    }

    private void ResetTiles()
    {
        for (int i = 0; i < GameManager.instance.tiles.Length; i++)
        {
            GameManager.instance.tiles[i].ResetTile();
        }
    }

}
